package cn.wolfcode.transfer.service.impl;

import cn.wolfcode.transfer.domain.Permission;
import cn.wolfcode.transfer.domain.Role;
import cn.wolfcode.transfer.domain.RolePermission;
import cn.wolfcode.transfer.mapper.PermissionMapper;
import cn.wolfcode.transfer.mapper.RoleMapper;
import cn.wolfcode.transfer.mapper.RolePermissionMapper;
import cn.wolfcode.transfer.qo.QueryObject;
import cn.wolfcode.transfer.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public int insert(Role role, Long[] ids) {
        int insert = roleMapper.insert(role);
        updateByPrimaryKey(role);
        if (ids != null)
            for (Long id : ids) {
                rolePermissionMapper.insert(role.getId(),id);
            }
        return insert;
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        int i = roleMapper.deleteByPrimaryKey(id);
        return i;

    }

    @Override
    public int updateByPrimaryKey(Role role) {
        int i = roleMapper.updateByPrimaryKey(role);

        return i;
    }

    @Override
    public Role selectByPrimaryKey(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }

    @Override
    public PageInfo<Role> getPageInfo(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.selectAll();
        return new PageInfo<Role>(roles);
    }


    @Override
    public void insert(Role role) {
        int insert = roleMapper.insert(role);

    }

    @Override
    public void updateByPrimaryKey(Role role, Long[] ids) {
        updateByPrimaryKey(role);
        rolePermissionMapper.deleteByRoleId(role.getId());
        if (ids != null)
            for (Long id : ids) {

                rolePermissionMapper.insert(role.getId(),id);
            }
    }

    @Override
    public List<Permission> selectPermission(Long id) {
        List<Permission> permissions = permissionMapper.selectByRoleId(id);
        return permissions;
    }

    public List<Permission> selectPermissionAll() {
        List<Permission> permissions = permissionMapper.selectAll();
        return permissions;
    }
}
